package com.lx.gulimall.seckill.service.impl;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.lx.common.to.MemberRespVo;
import com.lx.common.to.mq.SeckillOrderTo;
import com.lx.common.utils.R;
import com.lx.gulimall.seckill.feign.CouponFeignService;
import com.lx.gulimall.seckill.feign.ProductFeignService;
import com.lx.gulimall.seckill.interceptor.LoginUserInterceptor;
import com.lx.gulimall.seckill.service.SeckillService;
import com.lx.gulimall.seckill.to.SeckillSkuRedisTo;
import com.lx.gulimall.seckill.vo.SeckillSessionsWithSkus;
import com.lx.gulimall.seckill.vo.SeckillSkuVo;
import com.lx.gulimall.seckill.vo.SkuInfoVo;
import jodd.time.TimeUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @author lixun Email:lx3027@126.com
 * @create 2021-08-20 14:27
 */
@Service
@Slf4j
public class SeckillServiceImpl implements SeckillService {

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    CouponFeignService couponFeignService;

    @Autowired
    RedissonClient redissonClient;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    RabbitTemplate rabbitTemplate;

    private final String SESSION_CACHE_PREFIX = "seckill:sessions:";

    private final String SKUKILL_CACHE_PREFIX = "seckill:skus";

    private final String SKU_STOCK_SEMAPHORE = "seckill:stock:";

    @Override
    public void uploadSeckillSkuLatest3Days() {
        // 扫描需要参与秒杀的商品
        R session = couponFeignService.getLatest3DaySession();
        if (session.getCode() == 0) {

            // 上架商品
            List<SeckillSessionsWithSkus> sessionData = session.getData(new TypeReference<List<SeckillSessionsWithSkus>>() {
            });

            // 缓存到redis
            // 1.保存活动信息
            saveSessionInfos(sessionData);
            // 2.缓存活动的关联商品信息
            saveSessionSkuInfos(sessionData);
        }
    }

    public List<SeckillSkuRedisTo> blockHandler(BlockException e){
        log.error("getCurrentSeckillSkusResource被限流了...");
        return null;
    }

    // 返回当前时间参加的秒杀商品信息
    @SentinelResource(value = "getCurrentSeckillSkusResource",blockHandler = "blockHandler")
    @Override
    public List<SeckillSkuRedisTo> getCurrentSeckillSkus() {
        // 1、确定当前时间属于哪个秒杀场次
        // 获取当前时间
        long time = new Date().getTime();
        // 抛出异常的方式定义资源
        try (Entry entry = SphU.entry("seckillSkus")) {
            // 受保护的资源

            // 获取全部秒杀商品时间
            Set<String> keys = redisTemplate.keys(SESSION_CACHE_PREFIX + "*");
            // 遍历
            for (String key : keys) {
                // 替换
                // 如： seckill:sessions:4444404400404_55005055050
                // 值： 4444404400404_55005055050
                String replace = key.replace(SESSION_CACHE_PREFIX, "");
                // 截取
                String[] s = replace.split("_");
                // 开始时间
                Long start = Long.parseLong(s[0]);
                // 结束时间
                Long end = Long.parseLong(s[1]);

                // 当前时间在此秒杀商品之间
                if (time >= start && time <= end) {
                    // 2、获取这个秒杀场次需要的所有商品信息
                    List<String> range = redisTemplate.opsForList().range(key, -100, 100);
                    BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(replace);
                    List<String> list = hashOps.multiGet(range);
                    if (list != null) {
                        List<SeckillSkuRedisTo> collect = list.stream().map(item -> {
                            SeckillSkuRedisTo redisTo = JSON.parseObject(item.toString(), SeckillSkuRedisTo.class);
                            return redisTo;
                        }).collect(Collectors.toList());
                        return collect;
                    }
                    break;
                }
            }
        } catch (BlockException e) {
            log.error("资源被限流,{}", e.getMessage());
        }

        return null;
    }

    @Override
    public SeckillSkuRedisTo getSkuSeckillInfo(Long skuId) {
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
        Set<String> keys = hashOps.keys();
        if (keys != null && keys.size() > 0) {
            String reg = "\\d_" + skuId;
            for (String key : keys) {
                if (Pattern.matches(reg, key)) {
                    String s = hashOps.get(key);
                    SeckillSkuRedisTo redisTo = JSON.parseObject(s, SeckillSkuRedisTo.class);

                    long time = new Date().getTime();
                    Long startTime = redisTo.getStartTime();
                    if (time >= startTime && time <= redisTo.getEndTime()) {

                    } else {
                        redisTo.setRandomCode(null);
                    }
                    return redisTo;
                }
            }
        }
        return null;
    }

    // TODO: 2021/8/22 上架秒杀商品时，每个数据都应该有过期时间
    // TODO: 2021/8/22 秒杀后续的流程，简化了收获地址等信息
    @Override
    public String kill(String killId, String code, Integer number) {

        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();

        // 获取当前秒杀商品的详细信息
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
        String json = hashOps.get(killId);
        if (StringUtils.isEmpty(json)) {
            // 为空返回null
            return null;
        }

        SeckillSkuRedisTo redisTo = JSON.parseObject(json, SeckillSkuRedisTo.class);
        // 1、校验合法性 秒杀时间，随机码，对应关系，幂等性
        Long startTime = redisTo.getStartTime();
        Long endTime = redisTo.getEndTime();
        long time = new Date().getTime();
        long ttl = time - endTime;

        // 时间合法性
        // TODO: 2021/8/22 应该在保存redis的时候就给一个过期时间。过期的就不会获取到的
        if (time < startTime || time > endTime) {
            return null;
        }
        // 校验随机码和商品id
        String randomCode = redisTo.getRandomCode();
        // TODO: 2021/8/22 因为是直接通过killId获取的数据，这里就不再判断id了。
        if (!randomCode.equals(code)) {
            return null;
        }
        // 验证购物数量是否合理 判断是否大于限制的数量
        if (number > redisTo.getSeckillLimit()) {
            // 说明买过了
            return null;
        }

        // 检查这个人是否已经购买过 幂等性；只要秒杀成功，就去占位
        // userId_sessionId_skuId
        // SETNX
        String redisKey = memberRespVo.getId() + "_" + redisTo.getPromotionSessionId() + "_" + redisTo.getSkuId();
        // 单位毫秒
        Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(redisKey, number.toString(), ttl, TimeUnit.MILLISECONDS);
        if (aBoolean) {
            // 占位成功
            RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + randomCode);
            try {
                boolean b = semaphore.tryAcquire(number, 100, TimeUnit.MILLISECONDS);
                if (b) {
                    // 秒杀成功
                    // 快速下单
                    String timeId = IdWorker.getTimeId();
                    SeckillOrderTo orderTo = new SeckillOrderTo();
                    orderTo.setOrderSn(timeId);
                    orderTo.setMemberId(memberRespVo.getId());
                    orderTo.setNum(number);
                    orderTo.setPromotionSessionId(redisTo.getPromotionSessionId());
                    orderTo.setSeckillPrice(redisTo.getSeckillPrice());
                    rabbitTemplate.convertAndSend("order-event-exchange", "order.seckill.order", orderTo);
                    return timeId;
                }
                return null;
            } catch (InterruptedException e) {
                return null;
            }
        }

        return null;
    }

    private void saveSessionInfos(List<SeckillSessionsWithSkus> sessionData) {
        sessionData.stream().forEach(sessions -> {

            Long startTime = sessions.getStartTime().getTime();
            Long endTime = sessions.getEndTime().getTime();
            String key = SESSION_CACHE_PREFIX + startTime + "_" + endTime;
            Boolean aBoolean = redisTemplate.hasKey(key);
            if (!aBoolean) {
                List<String> collect = sessions.getRelationSkus().stream().map(item -> item.getPromotionSessionId().toString() + "_" + item.getSkuId().toString()).collect(Collectors.toList());
                redisTemplate.opsForList().leftPushAll(key, collect);
            }
        });
    }

    private void saveSessionSkuInfos(List<SeckillSessionsWithSkus> sessionData) {
        sessionData.stream().forEach(sessions -> {

            BoundHashOperations<String, Object, Object> ops = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);

            sessions.getRelationSkus().stream().forEach(seckillSkuVo -> {

                if (!ops.hasKey(seckillSkuVo.getPromotionSessionId().toString() + "_" + seckillSkuVo.getSkuId().toString())) {
                    String replace = UUID.randomUUID().toString().replace("_", "");
                    // 缓存商品

                    SeckillSkuRedisTo redisTo = new SeckillSkuRedisTo();

                    // 1. sku基本数据
                    R skuInfo = productFeignService.getSkuInfo(seckillSkuVo.getSkuId());
                    if (skuInfo.getCode() == 0) {
                        SkuInfoVo info = skuInfo.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                        });
                        redisTo.setSkuInfoVo(info);
                    }
                    // 2. sku的秒杀信息

                    BeanUtils.copyProperties(seckillSkuVo, redisTo);

                    // 3、设置上当前商品的秒杀时间
                    redisTo.setStartTime(sessions.getStartTime().getTime());
                    redisTo.setEndTime(sessions.getEndTime().getTime());

                    // 4.随机码
                    redisTo.setRandomCode(replace);

                    String s = JSON.toJSONString(redisTo);
                    ops.put(seckillSkuVo.getPromotionSessionId().toString() + "_" + seckillSkuVo.getSkuId().toString(), s);
                    // 5.使用库存作为分布式的信号量 限流：
                    RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + replace);
                    // 商品可以秒杀的数量作为信号量
                    semaphore.trySetPermits(seckillSkuVo.getSeckillCount().intValue());

                }
            });
        });
    }
}